package dichotomyMethod;

import org.junit.Test;

import java.util.Arrays;

/*
 *@description 在排序数组中查找第一个和最后一个数字
 *@author hkfan
 *@version 1.0
 *@create 2025/5/15 15:33
*/
public class LeetCode_34 {

    @Test
    public void test(){
        int[] res = searchRange(new int[]{5,7,7,8,8,10},8);
        System.out.println(res[0]);
        System.out.println(res[1]);

    }

    public int[] searchRange(int[] nums, int target) {
        //0. 定义返回结果
        int[] result = {-1,-1};
        //1. 判断是否存在
        int location = Arrays.binarySearch(nums, target);
        if (location<0){
            return result;
        }
        //2. 寻找起始位置和终止位置
        int left =location ,right =location;
        while (left>=1){
            if (nums[left-1]==target){
                left--;
            }else {
                break;
            }
        }
        while (right<=nums.length-2){
            if (nums[right+1]==target){
                right++;
            }else {
                break;
            }
        }
        result[0]=left;
        result[1]=right;
        return result;
    }

}
